import { defineStore } from 'pinia'
import bus from '@/bus'

const useChatBiStore = defineStore('chatbi', {
  state: () => ({
    activeAgent: null,
    chatList: [] as any[]
  }),
  actions: {
    setAgent(data:any) {
      this.activeAgent = data;
    },

    setChatList(data:any, isPush = true, reset = false) {
      if (reset) {
        this.chatList = []; 
      }
      this.chatList = isPush ? [...this.chatList, ...data] : [ ...data, ...this.chatList]

      // 向数字底部插入需要滚动到底部
      if(isPush) {
        setTimeout(() => {
          bus.emit('scrollToBottom')
        }, 0)
      }
    },
  
    updateChatSummaryWithStream(questionId: number, newContent: string | any, pathKey: string, increment: boolean) {
      const target = this.chatList.find(item => item.questionId === questionId)
      if (!target) {
        console.warn(`未找到 chatId 为 ${questionId} 的对话记录`)
        return
      }
    
      const keys = pathKey.split('.')
      let current: any = target
    
      // 遍历到倒数第二个 key，建立路径上的引用
      for (let i = 0; i < keys.length - 1; i++) {
        const key = keys[i]
        if (!(key in current)) {
          // 如果中间路径不存在，则创建空对象
          current[key] = {}
        }
        current = current[key]
      }
    
      // 最后一个 key，执行 += 操作
      const lastKey = keys[keys.length - 1]
      if (typeof current[lastKey] === 'string' && increment) {
        current[lastKey] += newContent
      } else if (Array.isArray(current[lastKey]) && increment) { 
        current[lastKey].push(newContent)
      }else {
        // 如果原值不是字符串（比如 undefined 或 null），直接赋值
        current[lastKey] = newContent
      }
      bus.emit('scrollToBottom')
    }
   
  }
})

export default useChatBiStore
